package com.caogen.refect;

import lombok.Data;

import javax.servlet.http.HttpServlet;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * Created by wangguangfei on 20/6/23.
 */
public class MethodReflect {

    public static void main(String[] args) {
        MethodReflect methodReflect = new MethodReflect();
        Method[] methods = methodReflect.getAllDeclaredMethods(new Child().getClass());
        Arrays.stream(methods).forEach(method -> System.out.println(method.getName()));
    }

    private Method[] getAllDeclaredMethods(Class<? extends Parent> c){
        Class clazz = c;

        Method[] allMethods;
        for(allMethods = null; !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
            Method[] thisMethods = clazz.getDeclaredMethods();
            if(allMethods != null && allMethods.length > 0) {
                Method[] subClassMethods = allMethods;
                allMethods = new Method[thisMethods.length + allMethods.length];
                System.arraycopy(thisMethods, 0, allMethods, 0, thisMethods.length);
                System.arraycopy(subClassMethods, 0, allMethods, thisMethods.length, subClassMethods.length);
            } else {
                allMethods = thisMethods;
            }
        }

        return allMethods != null?allMethods:new Method[0];
    }
}

@Data
class Parent{

    String name;
}

@Data
class Child extends Parent{
    String email;
}
